//
//  WebService.m
//  iSeal6100
//
//  Created by He Yuan on 13-1-25.
//  Copyright (c) 2013年 http://www.heyuan110.com. All rights reserved.
//

#import "WebService.h"
#import "APIClient.h"

#import "UIImage+fixOrientation.h"

#import "MBProgressHUD.h"

@implementation WebService

+(NSError *)configError:(NSInteger)errorcode msg:(NSString *)msg
{
    if (![APIClient isNetWork])
        errorcode = -1000;
    
    if (errorcode == 1)return nil;
    
    NSString *errormsg = [[APIClient sharedClient]errorMessageWithErrorCode:[NSString stringWithFormat:@"%d",errorcode]];
    
    if (errormsg==nil || [errormsg length]<1)
    {
         if(msg != nil)errormsg = msg;
    }
    
    if (errormsg) {
        NSError *error = [MSTool createError:errorcode localDescription:errormsg];
        return error;
    }
    else
    {
        errorcode = -404;
        errormsg = [[APIClient sharedClient]errorMessageWithErrorCode:[NSString stringWithFormat:@"%d",errorcode]];
    }
    NSError *error = [MSTool createError:errorcode localDescription:errormsg];
    return error;    
}


+(NSError *)configError:(NSInteger)errorcode
{
    return [WebService configError:errorcode msg:nil];
}



#pragma 发起GET请求
+(void)getRequestAction:(NSString *)action
                  param:(NSDictionary *)p
                success:(RequestSuccessBlock)sblock
                failure:(RequestFailureBlock)fblock
               progress:(UIView *)view
{
    if (view)[MSTool showHUD:HYLocalizedString(@"正在加载") inView:view];
    
    NSMutableDictionary *new_param =  [NSMutableDictionary dictionaryWithDictionary:p];
    [new_param setObject:action forKey:@"action"];
    
    //将dict--》json
    NSData *valuedata = [NSJSONSerialization dataWithJSONObject:new_param options:0 error:nil];
    NSString *vString = [[NSString alloc]initWithData:valuedata encoding:NSUTF8StringEncoding];
    
    //新的参数
    NSDictionary *new_p = [NSDictionary dictionaryWithObjectsAndKeys:
                       [APIClient sharedClient].protocolVersion,@"protocolv",
                       [APIClient sharedClient].appVersion,@"appv",
                       vString,REQ_JSON_KEY,
                       nil];
    
    [[APIClient sharedClient] getPath:@""
                           parameters:new_p
                              success:^(AFHTTPRequestOperation *operation, id JSON)
     {
         if (sblock)
         {
             NSString *msg = nil;
             NSInteger errorcode = 1;
             if (JSON && [JSON isKindOfClass:[NSDictionary class]])
             {
               msg = [JSON objectForKey:@"message"];
               errorcode = [[JSON objectForKey:@"status"] intValue];
             }
             sblock(JSON, [WebService configError:errorcode msg:msg]);
         }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         if (fblock)
         {
             error = [WebService configError:error.code];
             HYLog(@"%@",error);
             fblock(nil,error);
         }
     }];
}


+(void)cancelRequest:(NSString*)m
{
    [[APIClient sharedClient]cancelAllHTTPOperationsWithMethod:@"GET" path:m];
}

//取消所有的请求
+(void)cancelAllRequest
{
    [[[APIClient sharedClient] operationQueue] cancelAllOperations];
}

+(void)uploadImage:(UIImage *)uploadImage
             param:(NSDictionary *)p
         labelText:(NSString *)txt
           success:(RequestSuccessBlock)sblock
           failure:(RequestFailureBlock)fblock
{
   __block  MBProgressHUD *HUD;
    
    dispatch_async(dispatch_get_main_queue(),
                   ^{
                       UIWindow *w = [[[UIApplication sharedApplication] windows] lastObject];
                       HUD = [[MBProgressHUD alloc] initWithView:w];
                       [w addSubview:HUD];
                       HUD.mode = MBProgressHUDModeDeterminate;
                       HUD.progress = 0.0;
                       HUD.labelText = txt;
                       [HUD show:YES];
                   });
    
    APIClient *httpClient = [APIClient sharedClient];
    
    
    NSData *imageData = UIImageJPEGRepresentation([uploadImage fixOrientation], 0.5);
    
    NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST"
                                                                         path:[APIClient getPath:p]
                                                                   parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
        [formData appendPartWithFileData:imageData name:@"image" fileName:@"file.jpg" mimeType:@"image/jpeg"];
    }];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite)
    {
//        HYLog(@"bytesWritten--->%d",bytesWritten);
//        NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite);
        float progress = totalBytesWritten / (float)totalBytesExpectedToWrite;
//        HYLog(@"progress--->%f",progress);
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           HUD.progress = progress;
                       });
    }];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation,id responseObject)
    {
        NSDictionary *dict = [MSTool convertJsonToDictionary:[operation responseString]];
//        HYLog(@"%@",[MSTool convertJsonToDictionary:[operation responseString]]);
//        HYLog(@"%@",responseObject);
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           [HUD hide:YES];
                           [HUD removeFromSuperview];
                       });
        if (sblock) {
            sblock(dict,nil);
        }
    } failure:^(AFHTTPRequestOperation *operation,NSError *error)
    {
        dispatch_async(dispatch_get_main_queue(),
                       ^{
                           [HUD hide:YES];
                           [HUD removeFromSuperview];
                       });
        error = [WebService configError:error.code];
        HYLog(@"%@",error);
        fblock(nil,error);
    }];
    [operation start];
}


@end
